package com.ls.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalTime;

/**
 * 统一处理日志
 *
 * @author ls
 * @date 2021/1/3
 **/
@Component
@Aspect
public class ServiceLogAspect {

    private static final Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);

    /**
     * 切入点, 切点扫描 service 包下某个加了 @MyLog 注解的方法，如果只加注解类就会全部扫描
     */
    @Pointcut("execution(* com.ls.service.*.*(..))")
    public void pointcut() {

    }

    /**
     * joinPoint.getSignature() 获取该切点所在方法的名称
     * @param joinPoint
     */
    @Before("pointcut()")
    public void before(JoinPoint joinPoint) throws NoSuchMethodException {
        // 用户(ip)[1.2.3.4],在(时间)[xxx],访问了[com.nowcoder.community.service.xxx()].
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        // 请求地址
        String requestURI = request.getRequestURI();
        // 请求ip
        String ip = request.getRemoteHost();
        LocalDate date = LocalDate.now();
        LocalTime time = LocalTime.now().withNano(0);
        // 时间
        String now = date + " " + time;
        // 切入点类的class对象
        // Class<?> clazz = joinPoint.getTarget().getClass();
        // 切点所在方法的方法名
        // String methodName = joinPoint.getSignature().getName();
        // 切点所在方法
        // Method method = clazz.getMethod(methodName);
        // 获取方法上的注解
        // if (method.isAnnotationPresent(MyLog.class)) {
        //     MyLog myLog = method.getAnnotation(MyLog.class);
        //     String level = myLog.level();
        //     if ("debug".equals(level)) {
        //         logger.info("方法 {} 上标注了自定义日志注解，日志等级为 {} ", method, level);
        //     }
        // }

        String target = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        // 打印url
        logger.info("访问了 {} ", requestURI);
        logger.info("访问了 {} ", request.getContextPath() + request.getServletPath());
        logger.info("用户 [{}] ,在 [{}] ,访问了 [{}] .", ip, now, target);
    }

}
